package blog.filter;

import blog.common.BaseContext;
import blog.common.LoginFailException;
import blog.common.Result;
import blog.utils.JwtUtil;
import com.alibaba.fastjson.JSON;

import com.baomidou.mybatisplus.extension.api.R;
import io.jsonwebtoken.JwtException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 检查用户是否已经完成登录
 */
@WebFilter(filterName = "loginCheckFilter",urlPatterns = "/*")
//优先级，值越小，优先级越高
@Order(10)
@Slf4j
public class LoginCheckFilter implements Filter{
    //路径匹配器，支持通配符
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        if (request.getMethod().equals("OPTIONS")) {
            response.setHeader("Access-control-Allow-Origin", request.getHeader("Origin"));
            response.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS,PUT,DELETE");
            response.setHeader("Access-Control-Allow-Headers", request.getHeader("Access-Control-Request-Headers"));
            // 跨域时会首先发送一个option请求，这里我们给option请求直接返回正常状态
            if (request.getMethod().equals("OPTIONS")) {
                response.setStatus(200);
                return;
            }
        }


        //1、获取本次请求的URI
        String requestURI = request.getRequestURI();// /backend/index.html

        log.info("拦截到请求：{}",requestURI);

        //定义不需要处理的请求路径
        String[] urls = new String[]{
                "/user/login",
                "/user",
                "/videoType",
                "/video",
                "/file/upload",
                "/file/download",
        };

        //2、判断本次请求是否需要处理
        boolean check = check(urls, requestURI);

        //3、如果不需要处理，则直接放行
        if(check){
            log.info("本次请求{}不需要处理",requestURI);
            filterChain.doFilter(request,response);
            return;
        }





        //4-2、判断登录状态，如果已登录，则直接放行

            //获取请求头中的token
            String token = request.getHeader("token");
            if(token != null){
                try {
                    //去掉token前后的"
                    token = token.replace("\"", "");
                    //解析token，获取用户id
                    int id = (int) JwtUtil.getJws(token).getBody().get("id");
                    //将用户id存入ThreadLocal
                    BaseContext.setCurrentId(id);
                    log.info("用户已登录，id={}", id);

                    filterChain.doFilter(request, response);

                }catch (JwtException e){
                    log.info("用户未登录");
                    //5、如果未登录则返回未登录结果
                    //设置跨域
                    response.setHeader("Access-control-Allow-Origin", request.getHeader("Origin"));
                    response.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS,PUT,DELETE");
                    response.setHeader("Access-Control-Allow-Headers", request.getHeader("Access-Control-Request-Headers"));
                    response.setStatus(HttpStatus.OK.value());

                    returnJson(servletResponse, JSON.toJSONString(new Result(40027,"登录信息已失效,请重新登录", "登录信息已失效,请重新登录")));
                    return;

                }
            }else {
                log.info("用户未登录");
                //5、如果未登录则返回未登录结果
                //设置跨域
                response.setHeader("Access-control-Allow-Origin", request.getHeader("Origin"));
                response.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS,PUT,DELETE");
                response.setHeader("Access-Control-Allow-Headers", request.getHeader("Access-Control-Request-Headers"));
                response.setStatus(HttpStatus.OK.value());

                returnJson(servletResponse, JSON.toJSONString(new Result(40027,"登录信息已失效,请重新登录", "登录信息已失效,请重新登录")));
                return;
            }
    }

    /**
     * 路径匹配，检查本次请求是否需要放行
     * @param urls
     * @param requestURI
     * @return
     */
    public boolean check(String[] urls,String requestURI){
        for (String url : urls) {
            boolean match = PATH_MATCHER.match(url, requestURI);
            if(match){
                return true;
            }
        }
        return false;
    }
    private void returnJson(ServletResponse response, String json) {
        PrintWriter writer = null;
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        try {
            writer = response.getWriter();
            writer.print(json);

        } catch (IOException e) {
            log.error("response error", e);
        } finally {
            if (writer != null)
                writer.close();
        }
    }


}